#pragma once

#include "sdk-skype/Wi2Geo.Skype_h.h"

class CSkypePluginB;

class CSkypeController :
	public ATL::CWindowImpl<CSkypeController, ATL::CWindow, ATL::CWinTraits<WS_OVERLAPPEDWINDOW> >
{
	static UINT c_nAPIAttachMsg;
	static UINT c_nAPIDiscoverMsg;

	ATTACHMENT_STATUS m_nAttachmentStatus;
	HWND              m_hWndSkype;
	std::string       m_strUser;
	std::string       m_strUserLanguages;
	CSkypePluginB*    m_pOwner;

	static bool StartsWith
		( IN const char* azStr
		, IN const char* azPrefix
		)
	{
		return 0 == strncmp(azStr, azPrefix, strlen(azPrefix));
	}

public:

	CSkypeController
		( IN CSkypePluginB* pOwner
		)
		: m_pOwner(pOwner)
		, m_nAttachmentStatus(apiAttachUnknown)
		, m_hWndSkype(NULL)
	{
	}

	bool Discover()
	{
		m_nAttachmentStatus = apiAttachPendingAuthorization;

		return !!::SendMessage(HWND_BROADCAST, c_nAPIDiscoverMsg, (WPARAM)m_hWnd, 0);
	}

	ATTACHMENT_STATUS GetStatus() const
	{
		return m_nAttachmentStatus;
	}

	std::string GetUser() const
	{
		return m_strUser;
	}

	std::string GetUserLanguages() const
	{
		return m_strUserLanguages;
	}

	bool SendCommand(const std::string& cmd) const
	{
		if (!m_hWndSkype)
			return false;

		COPYDATASTRUCT cds = {0};

		cds.cbData = (DWORD)(cmd.length() + 1);
		cds.lpData = (PVOID)cmd.c_str();

#if TRACE_SKYPE
		ATLTRACE(_T("%hs\n"), cds.lpData);
#endif

		// send command to skype
		//
		return !!::SendMessage(m_hWndSkype, WM_COPYDATA, (WPARAM)m_hWnd, (LPARAM)&cds);
	}
public:

DECLARE_WND_CLASS_EX(_T("CWi2GeoSkypSkypeController"), 0, NULL)

BEGIN_MSG_MAP(CSkypeController)
	MESSAGE_HANDLER(WM_CLOSE, OnClose)
	MESSAGE_HANDLER(WM_COPYDATA, OnCopyData)
	MESSAGE_HANDLER(c_nAPIAttachMsg, OnSkypeAttach)
END_MSG_MAP()

	LRESULT OnSkypeAttach(UINT, WPARAM wParam, LPARAM lParam, BOOL&)
	{
		ATLTRACE(_T(__FUNCTION__) _T(": wParam %d lParam %d"), wParam, lParam);

		m_hWndSkype         = (HWND)wParam;
		m_nAttachmentStatus = (ATTACHMENT_STATUS)lParam;

		return 1;
	}

	LRESULT OnCopyData(UINT, WPARAM wParam, LPARAM lParam, BOOL&);

	LRESULT OnClose(UINT, WPARAM, LPARAM, BOOL&)
	{
		PostQuitMessage(0);
		return 1;
	}
};


